const { body, param } = require('express-validator')
const validate = require('../middleware/validate')
const Comment = require('../models/Comment')
const Article = require('../models/Article')
const User = require('../models/User')

//添加评论验证

exports.addComment = validate([
  body('content').notEmpty().withMessage('评论内容不能为空'),
  body('aid').notEmpty().withMessage('文章id不能为空'),
])
// 删除评论验证

exports.deleteComment = validate([
  param('id').notEmpty().withMessage('评论id不能为空'),
  param('id').isMongoId().withMessage('评论ID格式不正确'),
  param('id').custom(async (id, { req }) => {
    const comment = await Comment.findById(id).populate('uid')
    console.log('comment: ', comment)
    if (!comment) {
      return Promise.reject('评论不存在')
    }
    const user = await User.findById(req._id)
    if (!user.roles.includes('admin') && comment.uid._id.toString() !== req._id.toString()) {
      return Promise.reject('你没权限删除别人的评论')
    }
  }),
])
